package com.wifi.eshipewifi;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


import com.wifi.imp.MessageSend;
import com.wifi.imp.ViewListener;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

public class SocThread extends Thread {
//	private String ip = "10.0.0.113";
	private int port = 8888;
	private String TAG = "socket thread";
	private int timeout = 100000;
//	private int timeout = 100;

	public Socket client = null;
	PrintWriter out;
	BufferedReader in;
	public boolean isRun = true;
	public boolean isSend= true;
	Handler inHandler;
	Handler outHandler;
	Context ctx;
	private String TAG1 = "===Send===";
	SharedPreferences sp;
	String ip=null;//ip地址
	boolean isLoginActivity=false;//是否是在登录界面
	boolean socketSuccess=false;//socket是否连接成功

	public SocThread(Handler handlerin, Handler handlerout, Context context) {
		inHandler = handlerin;
		outHandler = handlerout;
		ctx = context;
		Log.i(TAG, "创建线程socket");
	}

	public SocThread(Handler handlerin, Handler handlerout, Context context,String ip,int timeout) {
		inHandler = handlerin;
		outHandler = handlerout;
		ctx = context;
		this.ip=ip;
		this.timeout=timeout;
		Log.i(TAG, "创建线程socket");
	}

	public SocThread(Handler handlerin, Handler handlerout, Context context, String ip) {
		inHandler = handlerin;
		outHandler = handlerout;
		ctx = context;
		this.ip=ip;
		Log.i(TAG, "创建线程socket");
	}

	public void setTimeout(int timeout){
		this.timeout=timeout;
	}


	public void setHandler(Handler handlerin, Handler handlerout){
		if(inHandler!=null & outHandler!=null){
			inHandler=null;
			outHandler=null;
		}
		inHandler = handlerin;
		outHandler = handlerout;
	}
	public boolean getSocketFalg(){
		return socketSuccess;
	}
	public void setIsLoginActivity(boolean isLoginActivity){
		this.isLoginActivity=isLoginActivity;
	}


	/**
	 * 连接socket服务器
	 */
	public void conn() {

		try {
			initdate();
			Log.i(TAG, "连接中……");
			if(client==null){
				//旧连接方式
//				client = new Socket(ip, port);
//				client.setSoTimeout(timeout);// 设置阻塞时间
				//新连接方式
				client = new Socket();
				SocketAddress socAddress = new InetSocketAddress(ip, this.port);
				client.connect(socAddress, timeout);//设置5秒连接 超时

				Log.i(TAG, "连接成功");
				in = new BufferedReader(new InputStreamReader(
						client.getInputStream()));
				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
						client.getOutputStream())), true);
				socketSuccess=true;
				Log.i(TAG, "输入输出流获取成功");
			}
			//TODO 要改
			((MessageSend)ctx).SendMessage("$first_connect;");
		} catch (UnknownHostException e) {
			Log.i(TAG, "连接错误UnknownHostException 重新获取");
			e.printStackTrace();
			socketSuccess=false;
			client=null;
			conn();
			if(isLoginActivity)
				((ViewListener)ctx).ViewSetListener();
		} catch (IOException e) {
			Log.i(TAG, "连接服务器io错误"+e.getMessage());
			socketSuccess=false;
			client=null;
			conn();
			if(isLoginActivity)
				((ViewListener)ctx).ViewSetListener();
		} catch (Exception e) {
			Log.i(TAG, "连接服务器错误Exception" + e.getMessage());
			e.printStackTrace();
			socketSuccess=false;
			if(isLoginActivity)
				((ViewListener)ctx).ViewSetListener();
		}
	}

	public void initdate() {
		sp = ctx.getSharedPreferences("SP", ctx.MODE_PRIVATE);
		if(ip==null){
		   ip = sp.getString("ipstr", ip);
		}
		port = Integer.parseInt(sp.getString("port", String.valueOf(port)));
		Log.i(TAG, "获取到ip端口:" + ip + ";" + port);
	}
 	final long time=5000;//3秒
	/**
	 * 实时接受数据
	 */
	@Override
	public void run() {
		Log.i(TAG, "线程socket开始运行");
		conn();
		Log.i(TAG, "1.run开始");
		String line = "";
		while (isRun) {
//		while (!client.isClosed() && !client.isInputShutdown()) {
			try {
				if (client != null) {
						Thread.sleep(time);
//					if(isSend){// TODO: 2016/6/13
					Log.i(TAG, "2.检测数据");
					while ((line = in.readLine()) != null) {
						Log.i(TAG, "3.getdata" + line + " len=" + line.length());
						Log.i(TAG, "4.start set Message");
						Message msg = inHandler.obtainMessage();
						msg.obj = line;
						inHandler.sendMessage(msg);// 结果返回给UI处理
						Log.i(TAG1, "5.send to handler");
						isSend=false;
					}
					if (!client.isClosed() && !client.isOutputShutdown()) {//socket断开且不是主动重新连接
						Message msg = outHandler.obtainMessage();
						msg.what = -1;
						outHandler.sendEmptyMessage(msg.what);// 结果返回给UI处理
//						break;
					}
				} else {
					Log.i(TAG, "没有可用连接");
					conn();
				}
			} catch (Exception e) {
				Log.i(TAG, "数据接收错误" + e.getMessage());
				e.printStackTrace();
				if(client.isClosed() || client.isInputShutdown()){
//					Message msg = inHandler.obtainMessage();
//					msg.what=-1;
//					inHandler.sendEmptyMessage(msg.what);
					client=null;
					conn();
				}
			}
		}

	}

	/**
	 * 发送数据
	 *
	 * @param mess
	 */
	public void Send(String mess) {
		try {
//			if (client != null) {
			if (!client.isClosed() && !client.isOutputShutdown()) {//并没有用
				Log.i(TAG1, "发送" + mess + "至"
						+ client.getInetAddress().getHostAddress() + ":"
						+ String.valueOf(client.getPort()));
				out.println(mess);
				out.flush();
				Log.i(TAG1, "发送成功");
				Message msg = outHandler.obtainMessage();
				msg.obj = mess;
				msg.what = 1;
				outHandler.sendMessage(msg);// 结果返回给UI处理
			} else {
				Log.i(TAG, "client 不存在");
				Message msg = outHandler.obtainMessage();
//				msg.obj = mess;
				msg.what = -1;
				outHandler.sendEmptyMessage(msg.what);// 结果返回给UI处理
				Log.i(TAG, "连接不存在重新连接");
//				conn();
			}

		} catch (Exception e) {
			Log.i(TAG1, "send error");
			e.printStackTrace();
		} finally {
			Log.i(TAG1, "发送完毕");
		}
	}

	/**
	 * 关闭所有连接
	 */
	public void closeAll() {
		try {
			if (client != null) {
				Log.i(TAG, "close in");
				in.close();
				Log.i(TAG, "close out");
				out.close();
				Log.i(TAG, "close client");
				client.close();
				inHandler.getLooper().quit();//关闭当前线程的消息循环机制
				outHandler.getLooper().quit();
				isRun=false;
			}
		} catch (Exception e) {
			Log.i(TAG, "close err");
			e.printStackTrace();
		}
	}

	/**
	 * 关闭所有连接
	 */
	public void close() {
		try {
			if (client != null) {
				Log.i(TAG, "close in");
				in.close();
				Log.i(TAG, "close out");
				out.close();
				Log.i(TAG, "close client");
				client.close();
				this.stop();
				isRun=false;
			}
		} catch (Exception e) {
			Log.i(TAG, "close err");
			e.printStackTrace();
		}
	}

	/**
	 * 关闭sockt连接
	 */
	public void closeSocket() {
		try {
			if (client != null) {
				Log.i(TAG, "close client");
				client.close();
				inHandler.getLooper().quit();//关闭当前线程的消息循环机制，如果不关闭 上一个activity中的hander可能还会接受消息
				outHandler.getLooper().quit();
			}
		} catch (Exception e) {
			Log.i(TAG, "close err");
			e.printStackTrace();
		}

	}
}
